package pkg

import (
	urlrand "crypto/rand"
	"encoding/json"
	redis1 "enjoy_xxz/internal/model/database/redis"
	"errors"
	"fmt"
	"github.com/go-redis/redis"
	"golang.org/x/crypto/bcrypt"
	"log"
	"math/big"
	"math/rand"
	"regexp"
	"strconv"
	"time"
)

// GetPwd 给密码加密
func GetPwd(pwd string) (string, error) {
	hash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
	return string(hash), err
}

// ComparePwd 比对密码
func ComparePwd(pwd1 string, pwd2 string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(pwd1), []byte(pwd2))
	if err != nil {
		return false
	} else {
		return true
	}
}

// 生成验证码
func NumCodeString() string {
	num := rand.Intn(9000) + 1000
	return strconv.Itoa(num)
}

// 判断电话格式
func MobileTypeBook(mobile string) bool {
	matchString, _ := regexp.MatchString("^1[3-9][0-9]{9}$", mobile)
	return matchString
}

// 短信限流  1分钟一次
func RedisLimit(phone string) error {
	key := "phone_:" + phone
	return redis1.RedisClient(func(rdb *redis.Client) error {
		get := rdb.Get(key)
		if get.Val() == "" {
			rdb.Set(key, "0", time.Minute)
		}
		result, err := rdb.Incr(key).Result()
		if err != nil {
			return err
		}
		fmt.Println(get.Val())
		if result != 1 {
			return errors.New("每分钟只能发送一次验证码")
		}
		return nil
	})
}

// 随机默认头像
var avatarURLs = []string{
	"https://iknow-pic.cdn.bcebos.com/c83d70cf3bc79f3d88d0eeb1a8a1cd11728b2979",
	"https://iknow-pic.cdn.bcebos.com/d000baa1cd11728b321c86a3dafcc3cec3fd2c79",
	"https://iknow-pic.cdn.bcebos.com/a5c27d1ed21b0ef498d992dfcfc451da81cb3e79",
	"https://iknow-pic.cdn.bcebos.com/58ee3d6d55fbb2fb3039dc8f5d4a20a44623dc19",
	"https://q8.itc.cn/q_70/images03/20241030/7e4e379bf5b84b6c9fb4a9fec3102d5d.jpeg",
	// ... 添加更多头像地址
}

// 随机昵称
var randName = []string{
	"嘿嘿", "哈哈", "你好", "超级无敌霸王龙",
	// ... 添加更多用户昵称
}

// getRandomIndex 生成一个指定范围内的随机索引
func getRandomIndex(max int) (int, error) {
	randomInt, err := urlrand.Int(urlrand.Reader, big.NewInt(int64(max)))
	if err != nil {
		return 0, err
	}
	return int(randomInt.Int64()), nil
}

// 随机头像  从 avatarURLs 中随机选择一个头像URL
func GetRandomAvatarURL() (string, error) {
	// 从头像地址切片中随机选择一个
	randomIndex, err := getRandomIndex(len(avatarURLs))
	if err != nil {
		return "", fmt.Errorf("生成随机索引失败: %v", err)
	}
	avatarURL := avatarURLs[randomIndex]
	return avatarURL, nil
}

// 随机昵称 从 randName 中随机选择一个昵称
func GetRandomNickname() (string, error) {
	randomIndex, err := getRandomIndex(len(randName))
	if err != nil {
		return "", fmt.Errorf("生成随机索引失败: %v", err)
	}
	nickname := randName[randomIndex]
	return nickname, nil
}

func GetImages(jsonImage string) []string {
	var imageData []string
	// 解析json格式图片
	fmt.Println("接受到图片：：", jsonImage)
	err := json.Unmarshal([]byte(jsonImage), &imageData)
	if err != nil {
		log.Println("解析图片数据失败:", err)
		return nil
	}
	if imageData == nil {
		imageData = []string{} // 如果解析失败，返回空切片
	}
	return imageData
}
